package com.nbpt.edu.commercesites.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

public class BeanUtils {

    // static关键字，静态方法，BeanUtils.copyPropertiesIgnoreNull
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        // 获取源对象的所有属性
        PropertyDescriptor[] sourceDescriptors = org.springframework.beans.BeanUtils.getPropertyDescriptors(source.getClass());

        for (PropertyDescriptor sourceDescriptor : sourceDescriptors) {
            try {
                // 获取属性名
                String propertyName = sourceDescriptor.getName();
                // 排除 class 属性
                if ("class".equals(propertyName)) {
                    continue;
                }
                // 获取源对象的属性值
                Object value = sourceDescriptor.getReadMethod().invoke(source);
                // 如果值不为 null，则复制到目标对象
                if (value != null) {
                    PropertyDescriptor targetDescriptor = org.springframework.beans.BeanUtils.getPropertyDescriptor(target.getClass(), propertyName);
                    if (targetDescriptor != null && targetDescriptor.getWriteMethod() != null) {
                        targetDescriptor.getWriteMethod().invoke(target, value);
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}
